import axios from 'axios'
import { Promise } from 'core-js'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截器
// 通过了http请求，返回2xx，3xx，
service.interceptors.response.use(
  response => {
    // 解构
    const { message, success } = response.data
    if (success === false) {
      return Promise.reject(new Error(message))
    } else {
      return response.data
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
